package com.ioidea.holland.jkListAct

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.heaton.blelibrary.ble.Ble
import cn.com.heaton.blelibrary.ble.BleRssiDevice
import cn.com.heaton.blelibrary.ble.model.BleDevice
import com.blankj.utilcode.util.ToastUtils
import com.ioidea.base.util.MyLogger
import com.ioidea.ble.en.EnumBleStatus
import com.ioidea.common.view.BaseActivity
import com.ioidea.holland.R
import com.ioidea.ble.Constant
import com.ioidea.holland.databinding.ActivityJkBleListBinding
import com.ioidea.holland.view.handPermission
import com.ioidea.holland.view.hideLoading
import com.ioidea.holland.view.showLoading
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class JkListAct : BaseActivity<ActivityJkBleListBinding>(), View.OnClickListener {

    private var emptyView: View? = null
    private val viewModel: JkListViewModel by viewModels()


    @Inject
    lateinit var jkListAdapter: JkListAdapter

    var bleDevs: ArrayList<BleRssiDevice> = ArrayList()


    override fun init() {
        initBleRv()
        requestPermissionsIfAboveM()
        initBleStatusListener()
        initViewModelListener()
        initOnClickListener()
        initRefreshListener()
    }


    /**
     * 监听蓝牙的开启  关闭   未连接  扫描中 连接中 已连接 监听服务开启成功
     */
    private fun initBleStatusListener() {
        viewModel.liveDataBleStatus.observe(this) { bleStatus ->

            when (bleStatus) {
                EnumBleStatus.ABLE -> {
                    //开启
                    MyLogger.hLog().i("开启")
                    binding.rlTipBlueTooth.visibility = View.GONE
                    binding.smartRefreshLayout.autoRefresh()
                }

                EnumBleStatus.DISABLE -> {
                    MyLogger.hLog().i("关闭")
                    binding.rlTipBlueTooth.visibility = View.VISIBLE
                    bleDevs.clear()
                    jkListAdapter.notifyDataSetChanged()
                }

                EnumBleStatus.CONNECTED -> {
                    MyLogger.hLog().i("CONNECTED")

                }

                EnumBleStatus.NOT_CONNECTED -> {
                    MyLogger.hLog().i("NOT_CONNECTED")
                }

                EnumBleStatus.CONNECTING -> {
                    MyLogger.hLog().i("CONNECTING")
                }

                EnumBleStatus.SUCCESS -> {
                    viewModel.removeTimeout()
                    toNextAct()
                }

                else -> {}
            }

        }

        viewModel.liveDataTimeOut.observe(this) { timeOut ->
            if (timeOut) {
                hideLoading()
                ToastUtils.showLong("超时")
            }
        }

    }

    override fun onPause() {
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        viewModel.setBleStatus()
    }


    /**
     * 监听scan  connect 回调的数据
     */
    private fun initViewModelListener() {
        viewModel.liveDataScanBleRssiDevice.observe(this) { device ->
            closeRefreshAni()
            addDevNotifyUI(device)
        }

        viewModel.liveDataTimeOut.observe(this) { device ->
            closeRefreshAni()
        }
    }


    private fun initOnClickListener() {
        binding.tvOpenBlueTooth.setOnClickListener(this)
    }

    private fun initRefreshListener() {
        binding.smartRefreshLayout.setOnRefreshListener {
            scan()
        }
    }
    private val REQUEST_CODE_PERMISSION = 1


    private val permissionHintMap = mutableMapOf<String, String?>()
    private fun requestPermissionsIfAboveM() {
        val requiredPermissions: MutableMap<String, String> = HashMap()
        requiredPermissions[Manifest.permission.BLUETOOTH] = "蓝牙"
        requiredPermissions[Manifest.permission.BLUETOOTH_ADMIN] = "蓝牙设置"
        requiredPermissions[Manifest.permission.ACCESS_COARSE_LOCATION] = "粗略位置"
        requiredPermissions[Manifest.permission.ACCESS_FINE_LOCATION] = "精确位置"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requiredPermissions[Manifest.permission.BLUETOOTH_SCAN] = "蓝牙扫描"
            requiredPermissions[Manifest.permission.BLUETOOTH_ADVERTISE] = "蓝牙广播"
            requiredPermissions[Manifest.permission.BLUETOOTH_CONNECT] = "蓝牙连接"
        }
        for (permission in requiredPermissions.keys) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionHintMap[permission] = requiredPermissions[permission]
            }
        }
        if (permissionHintMap.isNotEmpty()) {
            requestPermissions(permissionHintMap.keys.toTypedArray(), REQUEST_CODE_PERMISSION)
        }else{
            refresh()
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        handPermission(permissionHintMap as HashMap<String, String?>,permissions,grantResults){
            refresh()
        }
    }




    private fun refresh() {
        binding.smartRefreshLayout.autoRefresh()
    }


    private fun initBleRv() {
        binding.rvDev.layoutManager = LinearLayoutManager(this)
        jkListAdapter.setOnItemChildClickListener { adapter, view, position ->
            val data: List<BleRssiDevice> = jkListAdapter.data
            val bleRssiDevice: BleRssiDevice = data[position]
            Constant.bleRssiDevice = bleRssiDevice
            when (view.id) {
                R.id.btnWrite -> {
                    MyLogger.hLog().e("btnWrite:" + bleRssiDevice.isConnected)
                    showLoading(getString(R.string.bluetooth_loading_writing))
                    if (bleRssiDevice.isConnected) {
                        toNextAct()
                    } else {
                        viewModel.connect(bleRssiDevice)
                    }
                }

                R.id.btnConnect -> {
                    MyLogger.hLog().e("btnRead:" + bleRssiDevice.isConnected)
                    showLoading(getString(R.string.bluetooth_loading_loading))
//                    val connectDevice = viewModel.getConnectDevice()
                    if (bleRssiDevice.isConnected) {
                        toNextAct()
                    } else {
                        viewModel.connect(bleRssiDevice)
                    }


                }
            }
        }
        binding.rvDev.adapter = jkListAdapter
        jkListAdapter.setNewInstance(bleDevs)
        setEmptyView()
    }


    private fun setEmptyView() {
        if (null == emptyView) {
            emptyView = layoutInflater.inflate(R.layout.layout_empty_bluetooth, null)
            jkListAdapter.setEmptyView(emptyView!!)
        }
    }


    /**
     * 重新刷新蓝牙状态
     */
    private fun scan() {
        if (!Ble.getInstance<BleDevice>().isBleEnable) {
            closeRefreshAni()
            binding.rlTipBlueTooth.visibility = View.VISIBLE
            return
        }
        binding.rlTipBlueTooth.visibility = View.GONE
        bleDevs = ArrayList()
        jkListAdapter.setNewInstance(bleDevs)
        viewModel.scan(jkListAdapter.data)
    }

    private fun closeRefreshAni() {
        binding.smartRefreshLayout.finishRefresh()
        binding.smartRefreshLayout.finishLoadMore()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tvOpenBlueTooth -> Ble.getInstance<BleDevice>().turnOnBlueTooth(this)
            else -> {}
        }
    }


    private fun addDevNotifyUI(newSearchBle: BleRssiDevice) {
        bleDevs.add(newSearchBle)
        jkListAdapter.notifyDataSetChanged()
        binding.rvDev.smoothScrollToPosition(bleDevs.size - 1)
    }

    private fun toNextAct() {
        hideLoading()
//        startActivity(Intent(this@JkListAct, JkDetailAct::class.java))
    }


    override fun onDestroy() {
        super.onDestroy()
        viewModel.disconnect(Constant.bleRssiDevice)
    }


}